from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import GenericAPIView, CreateAPIView, UpdateAPIView
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from goods.serializers import SKUSerializer
from users import constants
from users.models import User, Address
from users.serializers import UserSerializer, EmailSerializer, AddressSerializer, AddressTitleSerializer, \
    UserDetailSerializer, HistorySerializer


# POST /browse_histories/
class HistoryView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = HistorySerializer

    # def post(self, request):
    #     """浏览记录的保存
    #
    #     # 1.获取sku_id进行校验(sku_id必传,sku_id对应的商品是否存在)
    #     # 2.在redis中保存登录用户的浏览记录
    #     # 3.返回应答,浏览记录保存成功
    #     """
    #
    #     # 1.获取sku_id进行校验(sku_id必传,sku_id对应的商品是否存在)
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     # 2.在redis中保存登录用户的浏览记录
    #     serializer.save()
    #
    #     # 3.返回应答,浏览记录保存成功
    #     return Response(serializer.data, status=status.HTTP_201_CREATED)
    def get(self, request):
        """浏览记录的获取
        # 从redis中取出用户浏览的商品id
        # 根据商品的id获取对应的商品数据
        # 将商品的数据序列化并返回
        """
        user = request.user

        # 从redis中取出用户浏览的商品id
        # 获取redis链接
        redis_conn = get_redis_connection('histories')

        history_key = 'history_%s' % user.id

        sku_ids = redis_conn.lrange(history_key, 0, -1)  # 返回的是一个列表,并且拿出来的都是byte例如[b'<sku_id>',....]

        # 根据商品的id获取对应的商品数据
        skus = []

        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)  # get(id=1) get(id='1) get(id=b'1')内部都会进行转换

            skus.append(sku)

        # 将商品的数据序列化并返回
        serializer = SKUSerializer(skus, many=True)
        return Response(serializer.data)

        # 将商品的数据序列化并返回


class UsernameCountView(APIView):
    def get(self, request, username):
        """获取用户名"""
        count = User.objects.filter(username=username).count

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


class MobileCountView(APIView):
    """手机号数量"""

    def get(self, request, mobile):
        """获取用户名"""
        count = User.objects.filter(mobile=mobile).count

        data = {
            'username': mobile,
            'count': count
        }

        return Response(data)


# class UserView(CreateModelMixin,GenericAPIView):
class UserView(CreateAPIView):
    # 指定模型视图使用的序列化器类
    serializer_class = UserSerializer
    # def post(self, request):
    #     """注册用户信息
    #     1.获取参数并进行校验(参数完整性,用户名是否存在,手机号格式,手机号是否存在,是否同意协议,两次密码是否相同,短信验证码)
    #     2. 创建并保存新用户的消息
    #     3. 返回应答,注册成功
    #     """
    #     # 获取参数并进行校验(参数完整性,用户名是否存在, 手机号格式, 手机号是否存在, 是否同意协议,两次密码是否相同, 短信验证码)
    #     # serializer = self.get_serializer(data=request.data)
    #     # serializer.is_valid(raise_exception=True)
    #     # # 2.创建并保存新用户的消息
    #     # serializer.save()
    #     #
    #     # # 3.返回应答, 注册成功
    #     # return Response(serializer.data, status=status.HTTP_201_CREATED)
    #     return self.create(request)


# 用户个人中心
# GET /user/
class UserDetailView(GenericAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    def get(self, request):
        """
        获取登录用户的个人信息
        # 获取登录用户
        # 将登录用户序列化返回
        """

        # 获取登录用户
        user = request.user

        # 将登录用户信息序列化并返回
        serializer = self.get_serializer(user)

        return Response(serializer.data)


# PUT /email/
# class EmailView(GenericAPIView):
class EmailView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):
        """返回登录用户"""
        return self.request.user
    # def put(self, request):
    #     """
    #     保存登录用户的邮箱
    #     1.获取参数并进行校验(email必传,邮箱格式)
    #     2.设置登录用户的邮箱并给邮箱发送验证邮件
    #     3.返回应答,邮箱设置成功
    #     """
    #
    #     # 1.获取参数并进行校验(email必传, 邮箱格式)
    #     # 获取登录用户
    #     user = request.user
    #
    #     # 获取参数进行校验
    #     serializer = self.get_serializer(user, request.data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     # 2.设置登录用户的邮箱并给邮箱发送验证邮件
    #     serializer.save()
    #
    #     # 返回应答,邮箱设置成功
    #     return Response(serializer.data)


# PUT /emails/verification/?token=<加密用户的信息>
class EmailVerifyView(APIView):
    def put(self, request):
        """
        用户邮箱验证
        1.获取token(加密用户的信息)并进行校验(token必传,token是否有效)
        2.设置用户的邮箱验证标记为True
        3.返回应答,邮箱验证成功
        """

        # 1.获取token(加密用户的信息)并进行校验(token必传,token是否有效)
        token = request.query_params.get('token')

        if token is None:
            return Response({'message': '缺少token参数'}, status=status.HTTP_400_BAD_REQUEST)

        # token是否有效
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '无效的token数据'}, status=status.HTTP_400_BAD_REQUEST)
        # 2.设置用户的邮箱验证标记为True
        user.email_active = True
        user.save()

        # 3.返回应答,邮箱验证成功
        return Response({'message': 'OK'})


class AddressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = AddressSerializer

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False).all()

    # POST/ addresses/
    def create(self, request):
        """
        保存新增地址数据
        1. 接收参数并进行校验(参数完整性,手机号格式)
        2. 创建并保存新增地址数据
        3. 返回应答,地址创建成功
        """
        # 用户地址是否超过上限
        count = request.user.addresses.filter(is_deleted=False).count()
        if count > constants.USER_ADDRESS_COUNT_LIMIT:
            return Response({'message': '保存地址数量已达到了上限'}, status=status.HTTP_400_BAD_REQUEST)
        # 1. 接收参数并进行校验(参数完整性,手机号格式)
        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        #
        # # 2. 创建并保存新增地址数据
        # serializer.save()
        #
        # # 3. 返回应答,地址创建成功
        # return Response(serializer.data, status=status.HTTP_201_CREATED)

        # 调用'CreateModeMixin'扩展类中create方法
        return super().create(request)

    # GET /addersses/
    def list(self, request):
        """展示登录用户所有地址信息"""
        # 获取当前用户的所有地址
        user = request.user
        addresses = self.get_queryset()

        # 将地址序列化并且返回
        serializer = self.get_serializer(addresses, many=True)

        response = {
            'user_id': user.id,  # 用户id
            'default_address_id': user.default_address_id,  # 默认地址id
            'limit': constants.USER_ADDRESS_COUNT_LIMIT,  # 地址上限
            'addresses': serializer.data  # 地址数据
        }

        return Response(response)

    # PUT /addresses/(?P<pk>\d+)/
    # def update(self, request, pk):
    #     """
    #     1.根据pk获取对应的地址数据
    #     2.获取参数并进行校验
    #     3.保存修改地址的数据
    #     4.返回应答,修改成功
    #     """
    #     # 根据pk获取相对应的地址数据
    #     address = self.get_object()
    #
    #     # 获取参数并进行校验
    #     serializer = self.get_serializer(address, data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     serializer.save()
    #
    #     # 返回应答,修改成功
    #     return Response(serializer.data)

    # DELETE /addresses/(?P<pk>\d+)/
    def destroy(self, request, pk):
        """
       1.根据pk获取指定地址
       2.将指定地址删除
       3.返回响应
        """

        # 1. 根据pk获取指定地址
        address = self.get_object()

        # 将指定地址进行逻辑删除
        address.is_deleted = True
        address.save()

        # 返回响应
        return Response(status=status.HTTP_204_NO_CONTENT)

    # 设置默认地址
    # /addresses/(?P<pk>\d+)/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        """
        1.根据pk获取用户的地址
        2.将地址设置为默认地址
        3.返回应答
        """
        user = request.user
        # 根据pk获取用户的地址
        address = self.get_object()

        # 将地址设置为默认地址
        # user.default_address = address
        user.default_address_id = address.id
        user.save()

        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # 设置地址标题
    # /addresses/(?P<pk>\d+)/title/
    @action(methods=['put'], detail=True)
    def title(self, request, pk):
        """
        1.根据pk获取用户的地址
        2.修改地址标题,并保存
        3.返回应答
        """

        # 根据pk获取用户的地址
        address = self.get_object()

        # 修改地址标题并保存
        serializer = AddressTitleSerializer(address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # 返回应答
        return Response(serializer.data)


# POST /authorizations/
class UserAuthorizeView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            return response